#include <iostream>
#include <pthread.h>
#include <vector>
#include <unistd.h>

#define NUM 5

int cnt = 0;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

// 条件变量
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *threadRoutine(void *args)
{
  uint64_t number = (uint64_t)args;
  std::cout << "pthread: " << number << " create success " << std::endl;

  while (true)
  {
    pthread_mutex_lock(&mutex);

    // 由于是测试，直接先让所有的线程都进入条件变量的队列休眠
    pthread_cond_wait(&cond, &mutex);
    printf("tread is running......, thread: %d, cnt: %d\n", number, cnt);

    cnt++;

    pthread_mutex_unlock(&mutex);
    // usleep(13);
  }

  return nullptr;
}

int main()
{
  // pthread_mutex_t lock;
  // pthread_mutex_init(&lock, nullptr);

  // pthread_cond_t cond;
  // pthread_cond_init(&cond, nullptr);

  std::vector<pthread_t> tids;
  for (uint64_t i = 0; i < NUM; i++)
  {
    pthread_t tid;
    pthread_create(&tid, nullptr, threadRoutine, (void *)i);
    tids.push_back(tid);
    usleep(1000);
  }
  sleep(3);
  std::cout << "man thread is ctrl" << std::endl;
  // 主线程来唤醒休眠的线程
  while (1)
  {
    sleep(1);
    pthread_cond_signal(&cond);
    std::cout << "signal is waked" << std::endl;
  }

  for (auto tid : tids)
  {
    pthread_join(tid, nullptr);
  }

  return 0;
}